package com.example.crossborderecommerce.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.crossborderecommerce.entity.*;
import com.example.crossborderecommerce.mapper.ProductAttributeMapper;
import com.example.crossborderecommerce.mapper.ProductBrandMapper;
import com.example.crossborderecommerce.service.IAdminService;
import com.example.crossborderecommerce.service.IProductAttributeService;
import com.example.crossborderecommerce.service.IProductBrandService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 产品品牌模块
 *
 * @author Yolanda
 * @since 2024-05-09
 */
@RestController
@Transactional
@RequestMapping("/product-brand")
public class ProductBrandController {
    @Resource
    IProductBrandService productBrandService;
    @Resource
    IAdminService adminService;
    @Resource
    ProductBrandMapper productBrandMapper;



    /**
     * 获取全部产品品牌
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/findPage")
    public Result findPage(@RequestParam(defaultValue = "") String name,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize){
        QueryWrapper<ProductBrand> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name", name);
        Page<ProductBrand> productBrandPage = productBrandService.page(new Page<>(pageNum,pageSize), queryWrapper);
        List<ProductBrand> productBrandList = productBrandPage.getRecords();
        for(ProductBrand productAttribute : productBrandList) {
            Admin admin = adminService.getById(productAttribute.getAdminId());
            productAttribute.setAdminName(admin.getName());
        }
        Page<ProductBrand> newProductAttributePage = new Page<>(pageNum, pageSize);
        newProductAttributePage.setRecords(productBrandList);
        newProductAttributePage.setTotal(productBrandPage.getTotal());
        return Result.success("成功查询所有产品品牌！",newProductAttributePage);
    }
    /**
     * 添加产品品牌
     * @param productBrand
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody ProductBrand productBrand) {
        boolean res = productBrandService.save(productBrand);
        if(res) {
            return Result.success("添加产品品牌成功！");
        }
        return Result.error("添加产品品牌失败！");
    }

    /**
     * 删除产品品牌
     * @param productBrand
     * @return
     */
    @PostMapping("/delete")
    public Result delete(@RequestBody ProductBrand productBrand){
        boolean res = productBrandService.removeById(productBrand);
        if (res){
            return Result.success("删除产品品牌成功！");
        }
        return Result.success("删除产品品牌失败！");
    }

    /**
     * 删除一系列产品品牌
     * @param ids
     * @return
     */
    @GetMapping("/deleteBatch")
    public Result deleteBatch(@RequestParam String ids) {
        List<String> productBrandIds = Arrays.stream(ids.split(",")).collect(Collectors.toList());
        boolean res = productBrandService.removeByIds(productBrandIds);
        if(res) {
            return Result.success("删除产品品牌成功");
        }
        return Result.error("删除产品品牌失败！");
    }

    /**
     * 获取全部产品品牌
     * @return
     */
    @GetMapping("/findAll")
    public Result findAll(){
        List<ProductBrand> productBrandList = productBrandService.list();
        if (productBrandList == null){
            return Result.error("获取全部产品品牌失败！");
        }
        return Result.success("获取全部产品品牌成功！",productBrandList);
    }

    /**
     * 修改产品品牌
     * @param productBrand
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody ProductBrand productBrand) {
        boolean res = productBrandService.saveOrUpdate(productBrand);
        if (res) {
            return Result.success("修改产品品牌成功！");
        }
        return Result.error("修改产品品牌失败！");
    }
    /**
     * 导出产品品牌
     * @param name
     * @param response
     * @return
     */
    @GetMapping("exportProductBrandList")
    public Result exportProductBrandList(@RequestParam(defaultValue = "") String name,
                                         HttpServletResponse response) {
        QueryWrapper<ProductBrand> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name", name);
        List<ProductBrand> productBrandList = productBrandService.list(queryWrapper);
        for(ProductBrand productBrand : productBrandList) {
            Admin admin = adminService.getById(productBrand.getAdminId());
            productBrand.setAdminName(admin.getName());

        }
        HSSFWorkbook wb = new HSSFWorkbook(); // 导出到excel文件中
        HSSFSheet sheet = wb.createSheet("表一");
        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        HSSFCell cell = row.createCell((short) 0);
        cell.setCellValue("ID");
        cell.setCellStyle(style);
        cell = row.createCell((short) 1);
        cell.setCellValue("品牌名称");
        cell.setCellStyle(style);
        cell = row.createCell((short) 2);
        cell.setCellValue("品牌简称");
        cell.setCellStyle(style);
        cell = row.createCell((short) 3);
        cell.setCellValue("创建人");
        cell.setCellStyle(style);
        cell = row.createCell((short)4);
        cell.setCellValue("创建时间");
        cell.setCellStyle(style);
        SimpleDateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < productBrandList.size(); i++) {
            row = sheet.createRow(i + 1);
            ProductBrand productBrand = productBrandList.get(i);
            row.createCell((short) 0).setCellValue(productBrand.getId());
            row.createCell((short) 1).setCellValue(productBrand.getName());
            row.createCell((short) 2).setCellValue(productBrand.getShortName());
            row.createCell((short) 3).setCellValue(productBrand.getAdminName());
            try {
                Date createTime = inputDateFormat.parse(productBrand.getCreateTime().toString()); // 假设 getCreateTime 返回的是 String
                row.createCell((short) 4).setCellValue(outputDateFormat.format(createTime));
            } catch (ParseException e) {
                row.createCell((short) 4).setCellValue(productBrand.getCreateTime().toString());
            }
        }
        String fileName = "exportProductBrandList.xls";
        // 用户下载
        try {
            ServletOutputStream outputStream = null;
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));
            outputStream = response.getOutputStream();
            wb.write(outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.success("exportProductBrandList");
    }
}
